package com.yzm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzm.pojo.Account;
import com.yzm.pojo.Admin;
import com.yzm.pojo.R;
import com.yzm.service.AccountService;
import com.yzm.service.AdminService;
import com.yzm.utils.MD5;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public R<Admin> login(HttpServletRequest request, @RequestBody Admin admin) {
        String password = admin.getPassword();
        password = MD5.encrypt(password);
        Admin resultAdmin = adminService.login(admin.getUsername(), password);
        if (resultAdmin != null) {
            request.getSession().setAttribute("admin",admin.getId());
            return R.success(resultAdmin);
        }
        return R.error("用户名或密码错误");
    }

    @GetMapping("/page")
    public R<Page> page(@RequestParam("page") int page,
                        @RequestParam("pageSize")int pageSize,
                        @RequestParam(value = "name",required = false) String name) {
        Page pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Strings.isNotEmpty(name),Account::getAccountName,name);
        accountService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }



    @PostMapping()
    public R addAccount(@RequestBody Account account) {
        try {
            accountService.save(account);
            return R.success("添加成功");
        } catch (Exception ex) {
            return R.error(ex.getMessage());
        }
    }

    @PutMapping()
    public R update(@RequestBody Account account) {
        try {
            accountService.updateById(account);
            return R.success("修改成功!");
        } catch (Exception ex) {
            return R.error(ex.getMessage());
        }
    }

    @GetMapping("/{id}")
    public R<Account> getById(@PathVariable Long id){
        Account account = accountService.getById(id);
        if(account != null) {
            return R.success(account);
        }
        return R.error("没有查询到对应员工信息");
    }

}
